if [ $# -eq 0 ];
then
    echo "usage: $0 SERVICE(服务名) PUBLISH(发布地址) NUM(服务个数)"
    exit
fi
#加载配置文件
declare -A map
function file2Map(){
        mapfile mapList < $1
        for line in ${mapList[@]}
        do
                arr=(${line//=/ })
                map[${arr[0]}]=${arr[1]}
        done
}
file2Map "conf/IP2User.conf"
file2Map "conf/Service2Idx.conf"

CURPWD=$PWD
SERVICE=$1
PUBLISH=$2
#用户名在IP2User.conf中配置
USERNAME=${map[$PUBLISH]}
#服务索引Service2Idx.conf中配置
IDX=${map[$SERVICE]}
NUM=`expr $3 - 1`
NACOS_SERVER=10.35.36.205
DOCKER_HUB=10.35.40.29:5000
VERSION=`docker images|grep "$DOCKER_HUB/$SERVICE" | awk 'NR==2 {print $2}'`
IMAGE_NAME=$SERVICE:$VERSION
echo "回滚版本$VERSION"
SHELL_FILENAME="$SERVICE"_publish.sh
echo "$SHELL_FILENAME"
#4个服务
for((ITEM=0;ITEM<=$NUM;ITEM++))
do
        echo "停止服务"
        #nacos下服务
        PORT=9$ITEM$IDX
        XXJPORT=1$PORT
curl --location --request PUT 'http://'${NACOS_SERVER}':8848/nacos/v1/ns/instance' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'serviceName=huantv-'${SERVICE}'' \
--data-urlencode 'ip='${PUBLISH}'' \
--data-urlencode 'port='${PORT}'' \
--data-urlencode 'metadata=preserved.register.source=SPRING_CLOUD' \
--data-urlencode 'enabled=false'
echo "下线服务$PUBLISH:$PORT"
        sleep 1
        echo "#自动生成脚本$SERVICE$ITEM" > $SHELL_FILENAME
        echo "sudo su -" >> $SHELL_FILENAME
        echo "docker pull $DOCKER_HUB/$IMAGE_NAME" >> $SHELL_FILENAME
        echo "docker stop $SERVICE$ITEM" >> $SHELL_FILENAME
        echo "docker rm $SERVICE$ITEM" >> $SHELL_FILENAME
        echo "docker run --name $SERVICE$ITEM -v /bak/logs/$SERVICE$ITEM:/logs --env PARAMS=\"-Dspring.profiles.active=prod -Dserver.port=$PORT -Dxxljob.port=$XXJPORT\" --network host -d $DOCKER_HUB/$IMAGE_NAME" >> $SHELL_FILENAME
        echo "exit" >> $SHELL_FILENAME
        echo "ssh $USERNAME@$PUBLISH < $SHELL_FILENAME"
        ssh $USERNAME@$PUBLISH < $SHELL_FILENAME
echo "等待服务启动完成"
        while true #等待服务起来
        do
                PROCESSNUM=`curl --location --request GET 'http://'${NACOS_SERVER}':8848/nacos/v1/ns/catalog/instances?serviceName=huantv-'${SERVICE}'&clusterName=DEFAULT&groupName=DEFAULT_GROUP&pageSize=10&pageNo=1&namespaceId=' |\
jq .list[] | jq -r '(.ip|tostring)+":"+(.port|tostring)+":"+(.enabled|tostring)' |\
                grep "$PUBLISH:$PORT:true" | wc -l | xargs echo`
                echo "服务数:$PROCESSNUM"
                if [ $PROCESSNUM -eq '0' ]; then
                        echo "等待..."
                        sleep 1
                else
                        echo "$PUBLISH:$PORT已上线"
                        echo "部署下一个"
                        break
                fi
        done

done

echo "$SERVICE 回滚完成"